/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
CAN_HandleTypeDef hcan;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_CAN_Init(void);
/* USER CODE BEGIN PFP */

static void CAN_Filter_Init(uint32_t id);
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan);
static void CAN_Start(void);
static uint32_t CAN_DataMessgae_Send(uint32_t sendID, uint32_t IDE, uint8_t data[]);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

CAN_RxHeaderTypeDef g_rxHearder = {0};
uint8_t g_payloadData[8] = {0};

/**
	*	@breif CAN filter init configration
	* @param can identifier
	*/
static void CAN_Filter_Init(uint32_t id)
{
	CAN_FilterTypeDef filter0 = {0};
	/*set: filter bank 0, FIFO 0, List Mode(0x07DF, 0x07E8), 32 bits wide*/
	filter0.FilterBank = 0; //bank 0
	filter0.FilterMode = CAN_FILTERMODE_IDLIST; //List Mode
	filter0.FilterScale = CAN_FILTERSCALE_32BIT; //32 bits wide
	filter0.FilterIdHigh = 0x0000; // identifier need to shift left 5 bits
	filter0.FilterIdLow = 0x0000;
	filter0.FilterMaskIdHigh = id << 5; // identifier need to shift left 5 bits
	filter0.FilterMaskIdLow = 0x0000;
	filter0.FilterFIFOAssignment = CAN_FILTER_FIFO0;
    filter0.SlaveStartFilterBank = 14;
	filter0.FilterActivation = CAN_FILTER_ENABLE;
	
	if(HAL_CAN_ConfigFilter(&hcan, &filter0) != HAL_OK) {
		Error_Handler();
	}
}

static void CAN_Start(void)
{
	//HAL_CAN_RegisterCallback(&hcan, HAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID, HAL_CAN_RxFifo0MsgPendingCallback);
#ifdef NODE1	
	CAN_Filter_Init(0x07E8);
#else 
	CAN_Filter_Init(0x07DF);
#endif
	HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
	HAL_CAN_Start(&hcan);
    HAL_CAN_WakeUp(&hcan);
}

static void CAN_Communication_Test(void)
{
#ifdef NODE1
	uint8_t msg1[8] = {0x02, 0x1a, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff,};
	uint8_t msg2[8] = {0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,};
    uint16_t i = 0;
	while(1) {
        HAL_CAN_GetRxMessage(&hcan, CAN_FILTER_FIFO0, &g_rxHearder, g_payloadData);
		CAN_DataMessgae_Send(0x07df, CAN_ID_STD, msg1);
		HAL_Delay(200);
		if(g_payloadData[0] == 0x02 && g_payloadData[1] == 0x5a && g_payloadData[2] == 0x80) {
			for(;;) {
				CAN_DataMessgae_Send(0x07df, CAN_ID_STD, msg2);
                HAL_Delay(200);
                HAL_CAN_GetRxMessage(&hcan, CAN_FILTER_FIFO0, &g_rxHearder, g_payloadData);
                HAL_Delay(200);
                if(g_payloadData[0] == 0x02 && g_payloadData[1] == 0x51 && g_payloadData[2] == 0x01) {
                    for(i = 0; i < 0xff; i++) {
                        CAN_DataMessgae_Send(0x07df, CAN_ID_STD, msg1);//1A 80
                    }
                    break;
                }
			}
            break;
		}
	}
#else 
	uint8_t msg1[8] = {0x02, 0x5a, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff,};
    uint8_t msg2[8] = {0x02, 0x51, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,};
    uint16_t i = 0;
	while(1) {
		HAL_Delay(200);
        HAL_CAN_GetRxMessage(&hcan, CAN_FILTER_FIFO0, &g_rxHearder, g_payloadData);
		if(g_payloadData[0] == 0x02 && g_payloadData[1] == 0x1a && g_payloadData[2] == 0x80) {
			for(;;) {
				CAN_DataMessgae_Send(0x07e8, CAN_ID_STD, msg1);
				HAL_Delay(200);
                HAL_CAN_GetRxMessage(&hcan, CAN_FILTER_FIFO0, &g_rxHearder, g_payloadData);
				if(g_payloadData[0] == 0x02 && g_payloadData[1] == 0x01 && g_payloadData[2] == 0x01) {
                    //send 51 01 five times, then stop send
                    for(i = 0; i < 0xff; i++) {
                        CAN_DataMessgae_Send(0x07e8, CAN_ID_STD, msg2);
                    }
					break;
				}
			}
			break;
		}
	}
#endif
	for(;;);
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_CAN_Init();
  /* USER CODE BEGIN 2 */
	CAN_Start();
	CAN_Communication_Test();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}



/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief CAN Initialization Function
  * @param None
  * @retval None
  */
static void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN1;
  hcan.Init.Prescaler = 9;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_4TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_3TQ;
  hcan.Init.TimeTriggeredMode = DISABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = ENABLE;
  hcan.Init.AutoRetransmission = DISABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */

  /* USER CODE END CAN_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
    
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */
/* RX FIFO 0 message Pending Callback*/
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
	if(hcan->Instance == CAN1) {
		HAL_CAN_GetRxMessage(hcan, CAN_FILTER_FIFO0, &g_rxHearder, g_payloadData);
	}
}

static uint32_t CAN_DataMessgae_Send(uint32_t sendID, uint32_t IDE, uint8_t data[])
{
	CAN_TxHeaderTypeDef txHeader = {0};
	uint32_t txMailbox;
	
	/*IDE param check*/
	if(IDE != CAN_ID_STD && IDE != CAN_ID_EXT) {
		return 0xFFFFFFFF;
	}
	txHeader.IDE = IDE;
	
	/* sendID param check */
	if(sendID > 0xffff && IDE == CAN_ID_STD) {
		return 0xFFFFFFFF;
	}
	
	if(IDE == CAN_ID_STD) {
		txHeader.StdId = sendID;
	} else {
		txHeader.ExtId = sendID;
	}
	
	txHeader.RTR = CAN_RTR_DATA;
	txHeader.DLC = 8;
    txHeader.TransmitGlobalTime = DISABLE;
	
	if(HAL_OK == HAL_CAN_AddTxMessage(&hcan, &txHeader, data, &txMailbox)) {
		return 0xFFFFFFF - 1;
	} else {
		return txMailbox;
	}
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
